package com.bjy.qa.agent.tools.script;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bjy.qa.agent.response.Response;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Map;

/**
 * JavaScript 脚本
 */
public class JavaScriptScript implements Script {

    @Override
    public Response run(Response response, Map<String, Object> globalParas, String script) {
        try {
            // 执行脚本
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            engine.eval(script);
            engine.put("response", response);
            engine.put("globalParas", globalParas);
            Invocable invocable = (Invocable) engine;
            Object result = invocable.invokeFunction("main");

            // 生成返回结果
            Map<String, Object> ret = new HashMap<>();
            ret.put("ret", result);
            String resultJson = JSON.toJSONString(ret, new SerializerFeature[]{SerializerFeature.WriteMapNullValue});
            Response responseReturn = new Response(resultJson, null);

            return responseReturn;
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
